package jp.dev7.enchant.tot.controller;

import java.util.List;
import java.util.Map;

import jp.dev7.enchant.tot.meta.MessageMeta;
import jp.dev7.enchant.tot.model.Message;

import org.slim3.controller.validator.RequiredValidator;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;

import com.google.appengine.repackaged.com.google.common.collect.Maps;

public class GetMessageController extends AbsJsonpController {

    private MessageMeta m = MessageMeta.get();

    @Override
    protected Object exec() throws Exception {
        Validators v = new Validators(request);
        v.add(m.toName, RequiredValidator.INSTANCE);
        if (!v.validate()) {
            Map<String, Object> result = Maps.newHashMap();
            result.put("status", "ERROR");
            return result;
        }

        List<Message> list =
            Datastore
                .query(m)
                .filter(m.toName.equal(asString(m.toName)))
                .sort(m.createdAt.desc)
                .limit(10)
                .asList();

        return list;
    }

}
